package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.EsSkuInfo;
import com.atguigu.gulimall.search.config.ElasticClientSearchConfig;
import com.atguigu.gulimall.search.service.ElasticSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ElasticSaveServiceImpl implements ElasticSaveService {
    @Resource
    RestHighLevelClient highLevelClient;

    @Override
    public Boolean productStatuUp(List<EsSkuInfo> esSkuInfo) throws IOException {
        //使用客户端把数据存进去
        //1.建议索引、将映射做好

        //2.批量插入sku数据
        //BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        for (EsSkuInfo skuInfo : esSkuInfo) {
            IndexRequest indexRequest = new IndexRequest("product");
            indexRequest.id(skuInfo.getSkuId().toString());
            String s = JSON.toJSONString(skuInfo);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse bulkResponse = highLevelClient.bulk(bulkRequest, ElasticClientSearchConfig.COMMON_OPTIONS);
        //处理插入结果
        boolean b = bulkResponse.hasFailures();
        if (b) {
            log.debug("商品上架失败");
        } else {
            List<String> collect = Arrays.stream(bulkResponse.getItems()).map(item -> {
                log.debug("商品上架成功+id" + item.getId());
                return item.getId();
            }).collect(Collectors.toList());
        }
        return b;
    }
}
